<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="app">
			<form action="" method="post">
				<input type="text" v-model="cityName"/>
				<input type="submit" value="查询" @click.prevent="searchWeather"/>
			</form>
			<hr >
			<div v-if="text !== '' ">
				天气: {{text}}<br>
				温度: {{temp}}
			</div>
		</div>
		<script type="text/javascript">
			const app = new Vue({
				el: '#app',
				data: {
					cityName: '',
					text: '',
					temp: 0,
					locationId: 0,
					geoAPI: 'https://geoapi.qweather.com/v2/city/lookup?',
					searchWeatherAPI: 'https://devapi.qweather.com/v7/weather/now?'
				},
				methods: {
					async searchWeather() {
						if(this.cityName == '') return
						this.text = '';
						this.temp = 0;
						const {geoAPI, searchWeatherAPI, cityName} = this;
						// 获取位置的id
						const res = await fetch(`${geoAPI}location=${cityName}&key=bb5ec1655dec440599c5677f440854b0`);
						const handleRes = await res.json()
		
						//查看是否找到id
						if(handleRes.code == 404) {
							alert('请输入合法的地名')
							this.cityName = ''
							return
						} 
						
						// 获取城市天气
						this.locationId = handleRes.location[0].id
						const weatherRes = await fetch(`${searchWeatherAPI}location=${this.locationId}&key=bb5ec1655dec440599c5677f440854b0`)
						const handleWeatherRes = await weatherRes.json()
						if(handleWeatherRes.code == 200) {
							this.text = handleWeatherRes.now.text
							this.temp = handleWeatherRes.now.temp
						}
					}
				}
			});
		</script>
	</body>
</html>
